package com.yuheadline.utils.encryption;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA加密工具类
 *
 * @author 高翔宇
 * @since 2024/4/30 周二 上午10:42
 */
public class SHAUtil {
    /**
     * 获取SHA-1加密后的字符串
     *
     * @param data 待加密的字符串
     * @return 加密后的字符串
     */
    public static String getHash(String data) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = data.getBytes();
        digest.update(bytes);
        byte[] hashedBytes = digest.digest();

        StringBuilder hexString = new StringBuilder();
        for (byte b : hashedBytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
